package com.neusoft.neuiotms.sap;

import org.mitre.dsmiley.httpproxy.ProxyServlet;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.core.task.TaskExecutor;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.stereotype.Component;

@Configuration
public class NeuiotmsSapConfiguration {

    @Value("${neuiotms.services:auth|dcam|dcom|dcvm|notice|static}")
    private String services;

    @Value("${cmdb.proxy.servlet-url:/cmdb/*}")
    private String cmdbProxyServletUrl;
    @Value("${cmdb.proxy.target-url}")
    private String cmdbProxyTargetUrl;

    /**
     * 单应用版本，需要替换API路径中的服务名
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean<UrlFilter> urlFilterRegistrationBean() {
        final FilterRegistrationBean<UrlFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new UrlFilter(this.services));
        registration.addUrlPatterns("/*");
        registration.setName("UrlFilter");
        registration.setOrder(100);
        return registration;
    }

    @Bean("mTaskExecutor")
    public TaskExecutor taskExecutor() {
        return new SimpleAsyncTaskExecutor();
    }

    /**
     * CMDB服务的反向代理，如果需要负载均衡特性，还是需要配置nginx等反向代理服务器 <br />
     * 优点：部署简单 <br />
     * 缺点：没有负载均衡等功能
     *
     * @return
     */
    @Bean
    @ConditionalOnProperty(name = "cmdb.proxy.enabled", havingValue = "true")
    public ServletRegistrationBean<ProxyServlet> servletRegistrationBean() {
        final ServletRegistrationBean<ProxyServlet> servletRegistrationBean =
                new ServletRegistrationBean<>(new ProxyServlet(), this.cmdbProxyServletUrl);
        servletRegistrationBean.addInitParameter("targetUri", this.cmdbProxyTargetUrl);
        servletRegistrationBean.addInitParameter(ProxyServlet.P_LOG, "true");
        return servletRegistrationBean;
    }

    @Component
    class ContainerFactoryConfigurer {
        ContainerFactoryConfigurer(final ConcurrentKafkaListenerContainerFactory<?, ?> factory) {
            factory.getContainerProperties().setMissingTopicsFatal(false);
        }
    }
}
